<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Models\User;
use App\Http\Controllers\Controller;
use Mockery\Exception;
use Overtrue\EasySms\EasySms;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
class PersionalController extends Controller
{
    private $company_id;
    private $user;
    private $role_flag;
    public function __construct()
    {
        $this->deviceType = $this->getDevice();
        if (\Auth::guard('api')->check()) {
            $user = \Auth::guard('api')->user();
            $data = User::find($user->id);
            if($this->deviceType){
//                PC
                $this->company_id = $data->company_id;
                $this->user = $data;
            }else{
//                APP
                $this->company_id = $data->appcompany_id;
                $this->user = $data;
                $this->user->company_id = $data->appcompany_id;
            }
            $company = \App\Models\Company::find($this->user->company_id);
            if(!empty($company)){
                $this->role_flag = $company->role_flag;
            }
        }
    }
    
    /**
     * 个人信息
     * @return $请求返回结果(array)
     */
    public function persionalInfo(Request $request){
        $userInfo = $this->user;
        $cmpName = DB::table('companies')->where('id',$userInfo->company_id)->first();
        $name = $userInfo->name ?? '';
        $mobile = $userInfo->mobile ?? '';
        $img =$userInfo->image ?? "";
        return response()->json(['code'=>200,'msg'=>'操作成功','data'=>['name'=>$name,'mobile'=>$mobile,'img'=>$img,'cmpName'=>$cmpName->name]]);
    }
    /**
     * 修改头像
     * @return $请求返回结果(array)
     */
    public function upImg(Request $request){
        $userInfo = $this->user;
        $file = $request->file('file');
        if (!$request->hasFile('file')) {
            $return = ['code'=>500,'msg'=>'上传文件为空或无效','data'=>[]];
            return response()->json($return);
        }
        if (!$request->file('file')->isValid()){
            $return = ['code'=>500,'msg'=>$file->getErrorMessage(),'data'=>[]];
            return response()->json($return);
        }
        if(!in_array($file->getClientOriginalExtension(),['png','jpg','jpeg'])){
            $return = ['code'=>500,'msg'=>'图片格式不允许','data'=>[]];
            return response()->json($return);
        }
        if($file->getClientSize() > $file->getMaxFilesize()){
            $return = ['code'=>500,'msg'=>'图片超过允许2M','data'=>[]];
            return response()->json($return);
        }
        if (!empty($file)) {
            $newFileName = md5(time() . rand(0, 10000)) . '.' . $file->getClientOriginalExtension();
            $savePath = 'persionalImg/' . date('Ymd', time());
            $result = $request->file('file')->move($savePath, $newFileName);
            $name = $savePath . '/' . $newFileName;
            if(!empty($result)){
                DB::table('users')->where('id',$userInfo->id)->update(['image'=>$name]);
                $p = $this->initialize();
                $icon = getenv('HTTP_URL_IMG').$name;
                $accRes = $p ->updateUinfo($userInfo->accid,$userInfo->name,$icon);
            }
            $return = ['code'=>200,'msg'=>'上传文件成功','data'=>['address'=>$name]];
            return response()->json($return);
        }
       
    }
    /**
     * 修改名称
     * @return $请求返回结果(array)
     */
    public function upName(Request $request){
        $userInfo = $this->user;
        $name = $request->input('name');
        if(mb_strlen($name,'utf8') > 12){
            return response()->json(['code'=>400,'msg'=>'姓名长度不符合','data'=>'']);
        }
        $userInfo->name = $name;
        DB::beginTransaction();
        try{
            DB::table('users')->where('id',$userInfo->id)->update(['name'=>$name]);
             DB::table('staff')->where([['company_id','=',$userInfo->company_id],['mobile','=',$userInfo->mobile]])->update(['name'=>$name]);
            DB::commit();
        } catch (\Exception $e){
            DB::rollback();//事务回滚
            return response()->json(['code'=>400,'msg'=>'姓名修改失败','data'=>'']);
        }
        $p = $this->initialize();
        $icon = getenv('HTTP_URL_IMG').$userInfo->image;
        $accRes = $p ->updateUinfo($userInfo->accid,$name,$icon);
        if($accRes['code'] != 200){
            return response()->json(['code'=>400,'msg'=>'姓名修改失败','data'=>'']);
        }
        return response()->json(['code'=>200,'msg'=>'姓名修改成功','data'=>'']);
    }
    /**
     * 我的收藏
     * @return $请求返回结果(array)
     */
    public function collectList(Request $request,$type){
        $userInfo = $this->user;
        $type = $type;
        if($type == 1){
//            简历
            $page = $this->page($request);
            $list = DB::table('collections')
                ->join('resumes', 'collections.obj_id', '=', 'resumes.id')
                ->join('users','resumes.user_id','users.id')
                ->where([['collections.user_id','=',$userInfo->id],['collections.status','=','0'],['collections.type','=',1],['resumes.status','=',0],['collections.company_id','=',$userInfo->company_id]])
                ->select( 'resumes.id','collections.created_at as time','resumes.name', 'resumes.is_job','resumes.company_name','resumes.image','resumes.position','resumes.sex','resumes.area','resumes.edu','resumes.step_name','users.name as owner_name')
                ->skip($page['skip'])
                ->take($page['take'])
                ->orderBy('time','desc')
                ->get();
        }else{
//            职位
            $page = $this->page($request);
            $list = DB::table('collections')
                ->join('positions', 'collections.obj_id', '=', 'positions.id')
                ->join('users','positions.user_id','=','users.id')
                ->where([['collections.user_id','=',$userInfo->id],['collections.status','=','0'],['collections.type','=',2],['positions.status','=',0],['is_use','=',1],['collections.company_id','=',$userInfo->company_id]])
               ->select( 'positions.id','positions.type','positions.name','positions.address','positions.nature','positions.min_salary','positions.max_salary','positions.edu','positions.dept_name','positions.person','positions.experience','positions.demand','positions.duty','positions.is_use','collections.created_at as time','users.name as owner_name')
                ->skip($page['skip'])
                ->take($page['take'])
                ->orderBy('time','desc')
                ->get();
        }
        if(!empty($list->toArray())){
            $type = 1;
        }else{
            $type  = 0;
        }
        return  response()->json(['code'=>200,'msg'=>'成功','data'=>['list'=>$list,'type'=>$type]]);
    }
    /**
     * 我的发布
     * @return $请求返回结果(array)
     */
    public function issueList(Request $request,$type){
        $userInfo = $this->user;
        $type = $type;
        if($type == 1){
//            简历
            $page = $this->page($request);
            $list = DB::table('resumes')
                ->join('users', 'resumes.owner_id', '=', 'users.id')
                ->where([['resumes.owner_id','=',$userInfo->id],['resumes.status','=','0'],['resumes.company_id',$userInfo->company_id]])
                ->select( 'resumes.id','resumes.name', 'resumes.image','resumes.position','resumes.sex','resumes.area','resumes.edu','resumes.step_name','resumes.is_job','resumes.company_name','resumes.job_date','users.name as owner_name')
                ->skip($page['skip'])
                ->take($page['take'])
                ->orderBy('id','desc')
                ->get();
        }else{
//            职位
            $page = $this->page($request);
            $list = DB::table('positions')
                ->join('users','positions.user_id','=','users.id')
                ->where([['positions.user_id','=',$userInfo->id],['positions.status','=','0'],['positions.is_use','=',1],['positions.company_id',$userInfo->company_id]])
                ->select( 'positions.id','positions.type','positions.name','positions.nature','positions.address','positions.experience','positions.min_salary','positions.max_salary','positions.edu','positions.person','positions.dept_name','positions.demand','positions.duty','positions.is_use','users.name as owner_name')
                ->skip($page['skip'])
                ->take($page['take'])
                ->orderBy('id','desc')
                ->get();
        }
        if(!empty($list->toArray())){
            $type = 1;
        }else{
            $type  = 0;
        }
        return  response()->json(['code'=>200,'msg'=>'成功','data'=>['list'=>$list,'type'=>$type]]);
    }
    /**
     * 修改密码
     * @return $请求返回结果(array)
     */
    public function changePwd(Request $request){
        $data = $request->all();
        $oldPwd = $request->input('oldPwd');
        $newPwd = $request->input('newPwd');
        $rePwd = $request->input('rePwd');
        $from = $request->input('from');
        $userInfo = $this->user;
        $accid = $userInfo->accid;
        $accessTokens = $userInfo->acc_token;
        $pwd = md5($oldPwd.$userInfo->salt);
        if($userInfo->password != $pwd){
            return  response()->json(['code'=>400,'msg'=>'旧密码错误','data'=>'']);
        }
        if($newPwd != $rePwd){
            return  response()->json(['code'=>400,'msg'=>'两次输入的密码不同','data'=>'']);
        }
        $salt = str_random(6);
        $password = md5($newPwd.$salt);
//        $result = DB::table('users')->where('id',$userInfo->id)->update(['password'=>$newPwd]);
//        if(!$result){
//            return  response()->json(['code'=>400,'msg'=>'密码修改失败','data'=>'']);
//        }
        $use = User::find($userInfo->id);
        DB::table('oauth_access_tokens')->where('user_id',$userInfo->id)->delete();
        $accessToken = $use->createToken('token');
        $token = $accessToken->accessToken;
        $tokenInfo = $accessToken->token.'#attributes';
        $res = str_replace('#attributes','',$tokenInfo);
        $tokenId = json_decode($res,true)['id'];
        if($from == 1){
            $userUp = User::where('id', $userInfo->id)
                ->update(['mobile_token' => $tokenId,'password'=>$password,'salt'=>$salt,'updated_at'=>time()]);
            DB::table('oauth_access_tokens')->where('id',$tokenId)->update(['expires_at'=>date('Y-m-d H:i:s',strtotime('+3 days'))]);
        }
        if($from == 2){
            $userUp = User::where('id', $userInfo->id)
                ->update(['pc_token' => $tokenId,'password'=>$password,'salt'=>$salt,'updated_at'=>time()]);
            DB::table('oauth_access_tokens')->where('id',$tokenId)->update(['expires_at'=>date('Y-m-d H:i:s',strtotime('+2 hours'))]);
        }
        if(empty($userUp)){
            return  response()->json(['code'=>400,'msg'=>'密码修改失败','data'=>[]]);
        }
        return  response()->json(['code'=>200,'msg'=>'密码修改成功','data'=>['userId'=>$userInfo->id,'companyId'=>$userInfo->company_id,'name'=>$userInfo->name,'token'=>$token,'accid'=>$accid,'accToken'=>$accessTokens]]);
    }
    /**
     * 切换企业
     * @return $请求返回结果(array)
     */
    public function changeCmp(Request $request){
        $userInfo = $this->user;
        $cid = $request->input('cid');
        $userInfo->company_id = $cid;
        $use = User::find($userInfo->id);
        $comapnyInfo = DB::table('companies')->where('id', $cid)->first();
        if (empty($comapnyInfo)) {
            return response()->json(['code' => 400, 'msg' => '不存在该公司', 'data' => '']);
        }
        $count = DB::table('staff')->where([['company_id', $cid], ['user_id', '!=', 0],['status','!=',1]])->count();
        $typeInfo = DB::table('staff')->where(['company_id'=>$cid,'mobile'=>$userInfo->mobile,'status'=>0])->first();
        $number = $config = Config::get('info.number');
        if(empty($typeInfo->user_id)){
            $count += 1;
        }
        $msg = '请联系该企业管理员购买软件';
        if ($count > $number+$comapnyInfo->order_num) {
            if($userInfo->id != $comapnyInfo->user_id){
                return response()->json(['code' => 400, 'msg' => $msg, 'data' => '']);
            }
        }
        if(!empty($comapnyInfo->order_updated_at) && time()>=$comapnyInfo->order_updated_at){
            if($userInfo->id != $comapnyInfo->user_id){
                return response()->json(['code' => 400, 'msg' => $msg, 'data' => '']);
            }
        }
        DB::table('oauth_access_tokens')->where('id',$userInfo->mobile_token)->delete();
        $accessToken = $use->createToken('token');
        $token = $accessToken->accessToken;
        $tokenInfo = $accessToken->token.'#attributes';
        $res = str_replace('#attributes','',$tokenInfo);
        $tokenId = json_decode($res,true)['id'];
        $userName = DB::table('staff')->where(['company_id'=>$cid,'mobile'=>$userInfo->mobile])->first();
        $userUp = User::where('id', $userInfo->id)
                ->update(['mobile_token' => $tokenId,'pc_token' =>'isnull','appcompany_id'=>$cid,'name'=>$userName->name,'updated_at'=>time()]);
        DB::table('oauth_access_tokens')->where('id',$tokenId)->update(['expires_at'=>date('Y-m-d H:i:s',strtotime('+3 days'))]);
        if(empty($userUp)){
            return  response()->json(['code'=>400,'msg'=>'企业切换失败','data'=>[]]);
        }
        DB::table('staff')
            ->where([['company_id','=',$cid],['mobile','=',$userInfo->mobile]])
            ->update(['user_id'=>$userInfo->id,'updated_at'=>time()]);
        return  response()->json(['code'=>200,'msg'=>'企业切换成功','data'=>['userId'=>$userInfo->id,'companyId'=>$userInfo->company_id,'name'=>$userName->name,'token'=>$token]]);
    }
    /**
     * 退出企业
     * @return $请求返回结果(array)
     */
    public function exitCmp(Request $request){
        $userInfo = \Auth::guard('api')->user();
        DB::beginTransaction();
        try{
            DB::table('users')
                ->where('id',$userInfo->id)
                ->update(['company_id'=>0]);
            DB::table('staff')
                ->where([['company_id',$userInfo->company_id],['mobile',$userInfo->mobile]])
                ->update(['status'=>'1']);
            DB::commit();
        } catch (\Exception $e){
            DB::rollback();//事务回滚
            return response()->json(['code'=>400,'msg'=>'退出企业失败失败','data'=>'']);
        }
        DB::table('oauth_access_tokens')->where('user_id',$userInfo->id)->delete();
        return response()->json(['code'=>200,'msg'=>'退出企业成功','data'=>'']);
    }
    //    初始化云信
    protected function initialize(){
        $config = Config::get('info.yunim');
        $appKey = $config['Appkey'];
        $appSecret = $config['appSecret'];
        $p = new ServerapiController($appKey,$appSecret,'curl');
        return $p;
    }
//    系统信息修改
    public function updateInfo(Request $request){
        $accid = $request->input('accid');
        $p = $this->initialize();
        $icon = getenv('HTTP_URL_IMG').'image/system.png';
//        $arr = [$accid];
//        $res =$p->getUinfos($arr);
//        dd($res);
        $accRes = $p ->updateUinfo($accid,'公告',$icon);
        dd($accRes);
    }
    
}